const TOKEN_KEY = 'token';
const UID_KEY = 'uid';

const isLogin = () => {
  return !!getToken();
};

const getToken = () => {
  let obj = localStorage.getItem(TOKEN_KEY);
  if(!obj) return '';
  if(obj[0]!='{') { // 兼容旧格式
    setToken(obj, 0);
    return obj;
  }
  let {token,date} = JSON.parse(obj);
  let now = new Date().getDate();
  if(date!=now) {
    localStorage.removeItem(TOKEN_KEY);
    return '';
  }
  return token;
};

const setToken = (token: string, userId: number) => {
  let date = new Date().getDate();
  localStorage.setItem(TOKEN_KEY, JSON.stringify({token,date}));
  if(userId) localStorage.setItem(UID_KEY, userId.toString());
};

const clearToken = () => {
  localStorage.removeItem(TOKEN_KEY);
};

const getUserId = () => {
  return parseInt(localStorage.getItem(UID_KEY) || '');
};

export { isLogin, getToken, setToken, clearToken, getUserId };
